#include "login.h"
#include "ui_login.h"
#include "regester.h"
#include "widget.h"
#include "mainwindow.h"
#include "user.h"
#include <QKeySequence>

User mainuser(0,"","","","");//初始化主用户


login::login(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::login)
{
    ui->setupUi(this);
    QPixmap image(":/image/logo.png");
    ui->imageLabel->setPixmap(image);
    ui->imageLabel->setScaledContents(true);
    QPixmap image_background(":/image/background.jpeg"); //设置登录界面的背景，使其自适应窗口大小
    ui->label_background->setPixmap(image_background);
    ui->label_background->setScaledContents(true);
    ui->loginButton->setShortcut(QKeySequence("Return"));//回车快捷键
}

login::~login()
{
    delete ui;
}

void login::on_returnButton_clicked()
{

            regester *signWindow = new regester;
            signWindow->show();
            QWidget::close();

}

void login::on_loginButton_clicked()
{
    QSqlQuery query(db);
    int id = ui->idlineEdit->text().toInt();
    QString pw = ui->pwlineEdit->text();
    QString sqlselect = QString("select password from regester where id='%1'; ").arg(id);// 查询本id的密码
    query.exec(sqlselect);
        if (query.next()) {
            QString value = query.value(0).toString(); // 获取查询结果的第一列的值
            if(value == pw)//判断密码是否正确
            {
                QString sqlselectall = QString("select password,name,signature from regester where id='%1'; ").arg(id);// 查询密码和名字
                query.exec(sqlselectall);
                if (query.next()) {
                    QString password = query.value(0).toString(); // 获取查询结果的第一列的值
                    QString name = query.value(1).toString();// 获取查询结果的第二列的值
                    QString signature = query.value(2).toString();// 获取查询结果的第三列的值
                    mainuser.setId(id);
                    mainuser.setName(name);
                    mainuser.setPassword(password);
                    mainuser.setSignature(signature);
                }
                qDebug() << "登录成功";
                QSound *soundEffect = new QSound( ":/sound/success.wav");
                soundEffect->play();
                Widget *ipWindow = new Widget;
                ipWindow->show();
                QWidget::close();
            }
            else{
                QSound *soundEffect = new QSound( ":/sound/error.wav");
                soundEffect->play();
                QMessageBox::warning(nullptr,tr("警告"),tr("密码错误"),QMessageBox::Ok);
            }
        } else {
            QSound *soundEffect = new QSound( ":/sound/error.wav");
            soundEffect->play();
            QMessageBox::warning(nullptr,tr("警告"),tr("id错误"),QMessageBox::Ok);
        }
}


